﻿using System;
using System.IO;
using System.Threading.Tasks;
using HtmlAgilityPack;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ServiceStack;
using ServiceStack.OrmLite;
using WebCoreAdmin.Common;
using WebCoreAdmin.Models;

namespace WebCoreAdmin.Controllers
{
    [Authorize]
    public class CkeditorController : Controller
    {
        private OrmLiteConnectionFactory Fac { get; }

        public CkeditorController(OrmLiteConnectionFactory fac)
        {
            Fac = fac;
        }

        [HttpPost]
        public async Task<IActionResult> Upload(string type)
        {
            if (Request.Form.Files.Count == 0) return Json(new { uploaded = 0 });
            var uploadfile = new UploadfileViewModel();

            var file = Request.Form.Files[0];
            var fileName = file.FileName;
            if (MimeType.ContentType(fileName) == "application/octet-stream")
                return Json(new { error = new { message = "不支持的格式" } });
            if (string.Equals(type, "Image", StringComparison.CurrentCultureIgnoreCase))
                if (!MimeType.IsImage(fileName))
                    return Json(new { error = new { message = "不支持的格式" } });
            if (string.Equals(type, "Flash", StringComparison.CurrentCultureIgnoreCase))
                if (!MimeType.IsFlash(fileName))
                    return Json(new { error = new { message = "不支持的格式" } });

            var rnd = new Random();
            var randomnum = rnd.Next(0, 999999);
            var path1 =
                $"Upload\\{DateTime.Now:yyyyMMdd}\\{DateTime.Now:yyyyMMddHHmmss}_{DateTime.Now.Ticks}_{randomnum:D6}{Path.GetExtension(fileName)}";
            var path = $"{AppDomain.CurrentDomain.BaseDirectory}{path1}";
            Directory.CreateDirectory(Path.GetDirectoryName(path));
            using (var stream = System.IO.File.Create(path))
            {
                await file.CopyToAsync(stream);
            }
            uploadfile.User = User.Identity.Name;
            uploadfile.Length = file.Length;
            uploadfile.Path = path;
            uploadfile.AddDateTime = DateTime.Now;
            using (var db = Fac.OpenDbConnection())
            {
                db.Insert(uploadfile);
                uploadfile = db.Single<UploadfileViewModel>(s => s.Path == path);
            }
            return Json(new { uploaded = 1, url = Url.Action("File", new { path = uploadfile.Id.ToString() })});
        }

        [HttpGet]
        public IActionResult File(string path)
        {
            UploadfileViewModel up;
            using (var db = Fac.OpenDbConnection())
            {
                up = db.SingleById<UploadfileViewModel>(path);
            }
            return PhysicalFile(up.Path, MimeType.ContentType(up.Path));
        }

        [HttpPost]
        public async Task<IActionResult> Form(string editor1, string ha)
        {
            var doc = new HtmlDocument();
            doc.LoadHtml(editor1);
            doc.DocumentNode.SelectNodes("//script").Each(_ => _.Remove());
            
            string html = doc.DocumentNode.OuterHtml;
            //todo:存入数据库

            return null;
        }

    }

}